package com.my.financial.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.my.financial.domain.FinancialAccount;
import com.my.financial.domain.FinancialService;
import com.my.financial.domain.User;

@Controller
@SessionAttributes("currUser")
public class AccountController {
	
	@Autowired
	private FinancialService financialService;

	@RequestMapping(value = "/accountManage", method = RequestMethod.GET)
	public ModelAndView accountManage(@ModelAttribute("currUser")User user) {
		ModelAndView mv = new ModelAndView("accountManage");
		mv.addObject(new FinancialAccount());
		List<FinancialAccount> list = financialService.findAllAccount(user.getId());
		return mv.addObject("list", list);
	}
	
	@RequestMapping(value = "/createAccount", method = RequestMethod.POST )
	public RedirectView createAccount(FinancialAccount financialAccount
			,@ModelAttribute("currUser")User user) {
		RedirectView mv = new RedirectView("accountManage");
		if(financialAccount!=null){
			financialAccount.setUser(user);
			financialService.saveAccount(financialAccount);
		}
		return mv;
	}
	@RequestMapping(value = "/deleteAccount", method = RequestMethod.GET )
	public RedirectView deleteAccount(String id,FinancialAccount financialAccount) {
		RedirectView mv = new RedirectView("accountManage");
		if(StringUtils.isNoneBlank(id)){
			financialService.deleteAccountById(Long.parseLong(id));
		}
		return mv;
	}
}
